module sw.client;
import nazo.http, nazo.string, std.conv, std.file, nazo.hmac_md5, std.uri, std.stdio, sw.siteconfig, std.contracts, std.base64;
/**
 * 見ているクライアントのクラスです。
 */
static struct Client{
  ///権限
  static enum Authority{
    None = 0,///無し
    Bot = 1,///ボット(権限に制限)
    Guest = 2,///一般
    Admin = 4,///管理人(何でもあり)
  }
  ///権限
  static Authority authority=Authority.Guest;
  private static string salt;
  ///塩の取得
  static string getSalt(){
    if(!salt){
      char[] salt;
      salt.length=8;
      int index;
      getBefores(Http.ip,'.',delegate void(string i){
        string tmp=std.string.toString(toLong(i),cast(uint)16);
        if(tmp.length==1){
          salt[index++]='0';
          salt[index++]=tmp[0];
        }else{
          salt[index++]=tmp[0];
          salt[index++]=tmp[1];
        }
      });
      this.salt = assumeUnique(salt);
    }
    return salt;
  }
  ///ユーザの名前の取得
  static string getName(SiteConfig* cfg){
    return (authority==Authority.Admin?"管理人("~cfg.manager~")":(authority==Authority.Bot?"制限ユーザ":"一般ユーザ")~"("~Http.ip~")");
  }
  ///初期化
  static Authority init(SiteConfig* cfg){
    if(Http.isBot||Http.acceptLanguage()=="")
      return (authority=Authority.Bot);
    string cookie=Http.cookie;
    if(cookie.length > 0){
      if(auto i=.find(cookie,";password=")!=-1)
        cookie=getBefore(cookie[i..$],';');
      else if(startWith(cookie,"password="))
        cookie=getBefore(cookie,';');
      else goto end;
      ubyte[16] tmp;
      cfg.passhash.hmacMd5(getSalt, tmp);
      if(cast(string)tmp==std.base64.decode(decodeComponent(cookie["password".length+1..$].replace(" ","+"))~"=="))
        return (authority=Authority.Admin);
    }
    end:
    if(cfg.personalMode)
      authority=Authority.Bot;
    return authority;
  }
}
